package message

import (
	"context"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"shop_webs/userop_web/api"
	"shop_webs/userop_web/forms"
	"shop_webs/userop_web/global"
	"shop_webs/userop_web/models"
	"shop_webs/userop_web/proto"
)

func List(ctx *gin.Context) {
	userId := ctx.GetInt("userId")
	claims, _ := ctx.Get("claims")

	currentUser := claims.(models.MyClaims)
	zap.S().Infof("当前用户是%d,权限是%d", userId, currentUser.AuthorityId)
	var messageRequest *proto.MessageRequest
	if currentUser.AuthorityId == 1 {
		messageRequest.UserId = int32(userId)
	}

	rsp, err := global.MessageClient.MessageList(context.Background(), messageRequest)
	if err != nil {
		zap.S().Errorw("[List] 查询 【留言】失败", "msg", err.Error())
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	if rsp.Total == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"total": 0,
		})
		return
	}

	/*		前端格式
			{
				"total":12,
				"data":[
					{
						"id":1,
						"goods_id":421,
						"goods_name":421,
						"goods_price":421,
						"goods_image":421,
						"nums":421,
						"checked":421,
					}
				]
			}
	*/
	var messageList []map[string]interface{}
	for _, message := range rsp.Data {
		messageList = append(messageList, map[string]interface{}{
			"id":      message.Id,
			"user_id": message.UserId,
			"type":    message.MessageType,
			"subject": message.Subject,
			"message": message.Message,
			"file":    message.File,
		})
	}

	ctx.JSON(http.StatusOK, gin.H{
		"total": rsp.Total,
		"data":  messageList,
	})
}
func New(ctx *gin.Context) {
	messageForm := forms.MessageForm{}
	if err := ctx.ShouldBind(&messageForm); err != nil {
		api.HandleValidatorError(err, ctx)
		return
	}

	rsp, err := global.MessageClient.CreateMessage(context.Background(), &proto.MessageRequest{
		UserId:      int32(ctx.GetInt("userId")),
		MessageType: messageForm.MessageType,
		Subject:     messageForm.Subject,
		Message:     messageForm.Message,
		File:        messageForm.File,
	})
	if err != nil {
		zap.S().Errorw("添加留言失败")
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"id": rsp.Id,
	})
	return
}
